package com.heima.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/11/18 10:56
 **/
@Component
@Slf4j
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    // 初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs"); // 小刀文档需要放行的路径
    }
    /**
     * @param exchange  封装了请求和响应
     * @param chain  过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1. 检查用户的请求路径是否属于白名单路径
        String path = request.getURI().getPath(); // /login/in
        for (String url : urlList) {
            if(path.contains(url)){
                // 放行请求
                return chain.filter(exchange);
            }
        }
        // 2. 获取请求头中的token  如果token不存在  直接终止请求 返回401
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
           return writeMessage(exchange,"请求中不包含 token信息");
        }
        // 3. 解析token  判断token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //-1：有效，0：有效，1：过期，2：过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            if(i<1){
                //   3.1  如果 token有效  取出token中的用户id   重新在设置到请求头中 并放行请求
                Object id = claimsBody.get("id");
                log.info("用户通过网关认证成功  当前登录用户id : {}",id);
                // 修改request
                request.mutate().header("userId",String.valueOf(id));
                // 修改exchange
                exchange.mutate().request(request);
                return chain.filter(exchange); // 放行
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        //   3.2  如果 token无效  终止请求  返回401
        return writeMessage(exchange,"token认证失败"); // 终止
    }


    /**
     * 返回错误提示信息
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
